import * as PIXI from "pixi.js";
import EditableObject from "./EditableObject";

class Person extends EditableObject {
  // 创建角色（头部等多个部位）
  // 修改部位

  constructor(app, personInfo) {
    super(app);

    this.obj = {};
    this.app = app;
    this.personInfo = personInfo;
    this.key = getRandomId();

    this.createPerson();
  }

  createDress() {
    this.createHair();
    this.createFace();
    this.createJacket();
    this.createTrousers();
    this.createAccessories();
  }

  createHair() {
    this.hair = this.createSprite(DataType.HAIR);
    this.obj.addChild(this.hair);
  }
  createFace() {
    this.face = this.createSprite(DataType.FACE);
    this.obj.addChild(this.face);
  }
  createJacket() {
    this.jacket = this.createSprite(DataType.JACKET);
    this.obj.addChild(this.jacket);
  }
  createTrousers() {
    this.trousers = this.createSprite(DataType.TROUSERS);
    this.obj.addChild(this.trousers);
  }
  createAccessories() {
    this.accessories = this.createSprite(DataType.ACCESSORIES);
    this.obj.addChild(this.accessories);
  }

  changeHair(dressInfo) {
    if (!this.hair) throw new Error("默认发型尚未初始化，请先选择角色！");
    this.hair.texture = getTextureFromCache(
      this.app,
      dressInfo.name,
      dressInfo.url
    );
  }

  changeFace(dressInfo) {
    if (!this.face) throw new Error("默认表情尚未初始化，请先选择角色！");
    this.face.texture = getTextureFromCache(
      this.app,
      dressInfo.name,
      dressInfo.url
    );
  }

  changeTrousers(dressInfo) {
    if (!this.trousers) throw new Error("默认裤子尚未初始化，请先选择角色！");
    this.trousers.texture = getTextureFromCache(
      this.app,
      dressInfo.name,
      dressInfo.url
    );
  }

  changeAccessories(dressInfo) {
    if (!this.accessories)
      throw new Error("默认饰品尚未初始化，请先选择角色！");
    this.accessories.texture = getTextureFromCache(
      this.app,
      dressInfo.name,
      dressInfo.url
    );
  }

  changeJacket(dressInfo) {
    if (!this.jacket) throw new Error("默认上衣尚未初始化，请先选择角色！");
    this.jacket.texture = getTextureFromCache(
      this.app,
      dressInfo.name,
      dressInfo.url
    );
  }

  getMaterialByType = (type) => {
    return this.personInfo.materialList.find((item) => item.type === type);
  };

  createPerson() {
    const container = new PIXI.Container();
    this.obj = container;

    this.createDress();

    container.x = 0;
    container.y = 0;

    this.setCenterPosition(container);
    this.app.stage.addChild(container);

    this.initObjEditable();
    this.makeSpriteEditable();
  }

  /**
   * 将Container放置在舞台中央
   */
  setCenterPosition(container) {
    const { screen } = this.app;
    container.x = screen.width / 2 + offsetList[addedNum++ % 3];
    container.y = screen.height / 2;
    // 这里设置人物的中心点，，不能转移给外container，因为他是以人物 进行缩放
    // 人物中心点如果没有设置，那么就会相对于左上角缩放了
    // 除非是设置外Contianer 缩放
    container.pivot.x = container.width / 2;
    container.pivot.y = container.height / 2;
  }
}
